//axios二次封装
import axios from 'axios'

// //导入进度条
// import NProgress from 'nprogress'
// //导入进度条样式
// import 'nprogress/nprogress.css'

import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials：true，//跨域请求时发送cookie
  timeout: 20000 // 请求超时
})

// 请求拦截器
service.interceptors.request.use((config) => {
  //进度条开始
  // NProgress.start()
  // 在发送之前做点什么
  const token = store.getters.token
  if (token) {
    // let each request carry token
    // ['X-Token'] is a custom headers key
    // please modify it according to the actual situation
    config.headers['token'] = token
  }
    return config
},error => {
  // 处理请求错误
  console.log(error) // for debug
  // NProgress.done()//进度条结束
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(
  /**
   * 如果您想获取http信息，如标头或状态，请返回response=>response
   * Please return  response => response
  */

  /**
   * 通过自定义代码确定请求状态
   * 这只是一个例子
   * 您也可以通过HTTP状态代码来判断状态
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    if (res.code !== 20000 && res.code !== 200) {
      Message({
        message: res.data || res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      // NProgress.done()//进度条结束
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    // NProgress.done()//进度条结束
    return Promise.reject(error)
  }
)

export default service
